package com.leetcodehot.problems;

public class problems230 {
    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    int count = 0;
    TreeNode pre = null;

    public int kthSmallest(TreeNode root, int k) {
        return dfs(root, k).val;
    }

    private TreeNode dfs(TreeNode root, int k) {
        if (root == null) return null;
        TreeNode left = dfs(root.left, k);
        if (left != null) return left;
        count++;
        if (count == k) return root;
        TreeNode right = dfs(root.right, k);
        return right;
    }
}
